package com.whcoding.test.common;

import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.WaitStrategies;
import com.google.common.base.Predicates;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @program: spring-boot-learning
 * @description:重试机制
 * @author: whcoding
 * @create: 2022-04-20 17:36
 **/
@Component
public class CustomizeRetryerUtils {
	private static final Logger log = LoggerFactory.getLogger(CustomizeRetryerUtils.class);

	/**
	 * 定义发送邮件的重试器
	 */
	private Retryer<Boolean> mailRetryer;

	/**
	 * 定义发送短信的重试器
	 */
	private Retryer<Boolean> msgRetryer;

	@Bean(value = "mailRetryer")
	public Retryer mailRetryer() {
		log.info("===========init mailRetryer==========");
		mailRetryer = RetryerBuilder.<Boolean>newBuilder()
				//retryIf 重试条件
				.retryIfException()
				.retryIfRuntimeException()
				.retryIfExceptionOfType(Exception.class)
				.retryIfException(Predicates.equalTo(new Exception()))
				.retryIfResult(Predicates.equalTo(false))
				//等待策略：每次请求间隔1s
				.withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
				//停止策略 : 尝试请求6次
				.withStopStrategy(StopStrategies.stopAfterAttempt(6))
				//时间限制 : 某次请求不得超过2s , 类似: TimeLimiter timeLimiter = new SimpleTimeLimiter();
				//	.withAttemptTimeLimiter(AttemptTimeLimiters.fixedTimeLimit(2, TimeUnit.SECONDS))
				.build();
		return mailRetryer;
	}

	@Bean(value = "msgRetryer")
	public Retryer msgRetryer() {
		log.info("=========init msgRetryer===========");
		msgRetryer = RetryerBuilder.<Boolean>newBuilder()
				//retryIf 重试条件
				.retryIfException()
				.retryIfRuntimeException()
				.retryIfExceptionOfType(Exception.class)
				.retryIfException(Predicates.equalTo(new Exception()))
				.retryIfResult(Predicates.equalTo(false))
				//等待策略：每次请求间隔0.2秒
				.withWaitStrategy(WaitStrategies.fixedWait(200, TimeUnit.MILLISECONDS))
				//停止策略 : 尝试请求9次
				.withStopStrategy(StopStrategies.stopAfterAttempt(9))
				.build();
		return msgRetryer;
	}
}

